package com.tensquare.article.controller;

import com.tensquare.article.pojo.Comment;
import com.tensquare.article.service.CommentService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author wz
 * @company 公司
 * @create 2020-02-09 10:26
 */
@RestController
@RequestMapping("comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @Autowired
    private RedisTemplate redisTemplate;

    //查询所有评论
    @GetMapping
    public Result findAll(){
      List<Comment> list = commentService.findAll();
        return new Result(true, StatusCode.OK,"查询成功",list);
    }
    //根据评论id查询评论数据
    @GetMapping("{commentId}")
    public Result findById(@PathVariable String commentId){
        Comment comment = commentService.findById(commentId);
        return new Result(true,StatusCode.OK,"查询成功",comment);
    }
    //新增评论
    @PostMapping
    public Result save(@RequestBody Comment comment){
        commentService.save(comment);
        return new Result(true,StatusCode.OK,"新增成功");
    }
    //修改评论
    @PutMapping("{commentId}")
    public Result update(@PathVariable String commentId, @RequestBody Comment comment){
        comment.set_id(commentId);
        commentService.updateById(comment);
        return new Result(true,StatusCode.OK,"修改成功");
    }
    //删除评论
    @DeleteMapping("{commentId}")
    public Result delete(@PathVariable String commentId){
        commentService.deleteById(commentId);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    //根据文章id查询评论列表
    @GetMapping("article/{articleId}")
    public Result findByArticleId(@PathVariable String articleId){
        List<Comment> list =commentService.findByArticleId(articleId);
        return new Result(true,StatusCode.OK,"查询文章评论成功",list);
    }
    //根据评论id点赞
    @PutMapping("thumbup/{commentId}")
    public Result thumbup(@PathVariable String commentId){
        //把用户点赞信息保存到redis中
        //每次点赞之前先查询用户点赞信息
        //如果没有点赞信息,用户可以点赞
        //如果有点赞信息,用户不能重复点赞

        //模拟用户id
        String userId = "123";

        //查询用户点赞信息,根据用户id和评论id
        Object flag = redisTemplate.opsForValue().get("thumbup_"+userId+"_"+commentId);
        //判断是否存在点赞信息
        if (flag==null){
            //点赞
            commentService.thumbup(commentId);
            //保存点赞信息
            redisTemplate.opsForValue().set("thumbup_"+userId+"_"+commentId,1);
            return new Result(true,StatusCode.OK,"点赞成功");
        }
        //不为空
        return new Result(false,StatusCode.REPERROR,"不能重复点赞");


    }
}
